<?php
/*
 * @Date: 2020-05-03 22:03:52
 * @名称: 
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2021-02-04 22:47:02
 * @FilePath: /Site/app/useradmin/controller/ClassifiedAndTags.php
 */

namespace app\useradmin\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\View;

class ClassifiedAndTags extends BaseController
{
    public function TagCatalogue()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";

        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        // 
        $tagList = Db::table('tags')
            ->alias('tags')
            ->join('user_info user_info', "user_info._id = tags.user_id")
            ->field([
                "user_info.name as creator", //发布人
                "tags.tag_name as tag_name", //标签名
                "tags._id as _id", //标签id
                "tags.state as state", //标签状态
            ])
            ->order('tags.id desc')
            ->select();
        return view('/ClassifiedAndTags/TagCatalogue/TagCatalogue', [
            'springboard' => config("globalsettings.PictureSpringboard"), //封面加速器地址
            "url" => 'http://' . $_SERVER['HTTP_HOST'] . "/",
            "tagList" => $tagList, //所有分类
            "hashHmac_toKen" => EncryptedData($encodeData, 3600, $key1, $key2), //!解密传入的用户信息,
        ]);
    }
    public function TagCatalogueUpdateState()
    {
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        # 更新分类状态
        $class_id =  input("get.tag_id");
        $title =  input("post.title");

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";
        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        $ParseUserToken = VerificationToken(input("post.token"), $encodeData, $key1, $key2);
        if ($ParseUserToken['code'] != 200) {
            return json($ParseUserToken);
        }

        $userJurisdiction = selectSuperUserJurisdiction($user_info['_id'], ['edit_class_info']);
        if ($userJurisdiction['code'] != 200) {
            return json($userJurisdiction);
        }
        if ($userJurisdiction['data']['state'] != 1) { //判断用户状态 必须是正常
            return json_decode(errorJsonReturn("User-10003")->getContent(), true);
        }
        if ($userJurisdiction['data']['edit_class_info'] != 1) { //判断用户权限 1代表有权限操作
            return json_decode(errorJsonReturn("User-10004")->getContent(), true);
        }

        $classInfo = Db::table('tags')
            ->where([
                "_id" => $class_id,
                "tag_name" => $title,
            ])
            ->field(["state"])
            ->find();

        if (!$classInfo) {
            return errorJsonReturn('Parameter validation failed');
        }
        if ($classInfo['state'] == 1) {
            $update = [
                "state" => 0,
            ];
        } else {
            $update = [
                "state" => 1,
            ];
        }
        try {
            Db::table('tags')
                ->where([
                    "_id" => $class_id,
                    "tag_name" => $title,
                ])
                ->update($update);
            return successJsonReturn(["state" => $update['state']]);
        } catch (\Throwable $th) {
            return errorJsonReturn('发生意外错误', "发生意外错误");
        }
    }

    public function tagDelete()
    {
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        # 更新分类状态
        $class_id =  input("get.tag_id");
        $title =  input("post.title");

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";
        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        $ParseUserToken = VerificationToken(input("post.token"), $encodeData, $key1, $key2);
        if ($ParseUserToken['code'] != 200) {
            return json($ParseUserToken);
        }

        $userJurisdiction = selectSuperUserJurisdiction($user_info['_id'], ['edit_class_info']);
        if ($userJurisdiction['code'] != 200) {
            return json($userJurisdiction);
        }
        if ($userJurisdiction['data']['state'] != 1) { //判断用户状态 必须是正常
            return json_decode(errorJsonReturn("User-10003")->getContent(), true);
        }
        if ($userJurisdiction['data']['edit_class_info'] != 1) { //判断用户权限 1代表有权限操作
            return json_decode(errorJsonReturn("User-10004")->getContent(), true);
        }

        $classInfo = Db::table('tags')
            ->where([
                "_id" => $class_id,
                "tag_name" => $title,
            ])
            ->field(["state"])
            ->find();

        if (!$classInfo) {
            return errorJsonReturn('Parameter validation failed');
        }
        try {
            Db::table('tags')
                ->where([
                    "_id" => $class_id,
                    "tag_name" => $title,
                ])
                ->delete();
            return successJsonReturn(["state" => "1"]);
        } catch (\Throwable $th) {
            return errorJsonReturn('发生意外错误', "发生意外错误");
        }
    }

    public function ClassifiedCatalogue()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";

        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        // 
        $classifiedList = Db::table('classified_catalogue')
            ->alias('classified_catalogue')
            ->join('user_info user_info', "user_info._id = classified_catalogue.user_id")
            ->field([
                "classified_catalogue.title", //分类名
                "classified_catalogue.original_name", // 文件名保存名字
                "classified_catalogue.path", //图片路径
                "classified_catalogue.file_server", //图片服务器地址
                "classified_catalogue.is_web", //是否是网页
                "classified_catalogue.active", //是否置顶
                "classified_catalogue.link", //要是网页的话网页的链接
                "classified_catalogue.description", //描述
                "classified_catalogue._id", //分类id
                "classified_catalogue.enable", //是否启用
                "classified_catalogue.state", //状态
                "classified_catalogue.id as data_base_id", //是否启用
                "user_info.name as creator", //发布人
            ])
            ->order('classified_catalogue.id desc')
            ->select();
        return view('/ClassifiedAndTags/Classified/Classified', [
            'springboard' => config("globalsettings.PictureSpringboard"), //封面加速器地址
            "url" => 'http://' . $_SERVER['HTTP_HOST'] . "/",
            "classifiedList" => $classifiedList, //所有分类
            "hashHmac_toKen" => EncryptedData($encodeData, 3600, $key1, $key2), //!解密传入的用户信息,
        ]);
    }



    public function EditClassified()
    {

        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";
        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        $EncryptedToken = input("get.token");
        $title = input("get.title");
        $class_id = input("get.class_id");
        $ParseUserToken = VerificationToken($EncryptedToken, $encodeData, $key1, $key2);
        if ($ParseUserToken['code'] != 200) {
            return json($ParseUserToken);
        }

        $class_info =  Db::table('classified_catalogue')
            ->where([
                "_id" => $class_id,
                "title" => $title,
            ])
            ->field([
                "title",
                "is_web",
                "active as is_top",
                "link",
                "description",
                "enable as is_enable",
                "file_server",
                "path",
                "original_name",
            ])
            ->find();
        $time = time();
        if ($class_info) {
            $establish = ["establish" => false, "time" => $time];
            $view = "ClassifiedAndTags/EditClassified/EditClassified";
        } else {
            $establish = [
                "establish" => true, "time" => $time
            ];
            $view = "ClassifiedAndTags/CreateClassification/CreateClassification";
        }
        $updateImage = hash_hmac("sha256", $class_id . $time, config("useradminConfig.useradmin_Edit_EditComicsInfo_sha256Encryption")); //上传图片所验证的id
        return view($view, [
            "useradmin" => 'http://' . $_SERVER['HTTP_HOST'] . "/useradmin/",
            "token" => $token,
            "class_id" => $class_id,
            'springboard' => config("globalsettings.PictureSpringboard"), //封面加速器地址
            "class_info" => $class_info,
            'time' => $time,
            'updateImage' => $updateImage,
            'image_host' => config("GlobalSettings.image_sever_cover"),
            "establish" => authcode(json_encode($establish), 'encode', config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode")), //!解密传入的用户信息,
        ]);
    }
    public function PreservationClassInfo() //保存分类数据 
    {
        $token = cookie("Authorization");;
        if ($token != input("post.token")) { //传入的token和 cookie 的token不一致
            return json_decode(errorJsonReturn("Token-10002")->getContent(), true);
        }
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $class_id = input("get.class_id");
        $title = trim(input('post.title'));
        $description = input('post.description');
        $web = input('post.web');
        $is_top = input('post.is_top');
        $is_enable = input('post.is_enable');
        $coverList = input('post.coverList');
        $establish = input('post.establish'); //是否创建漫画


        if ($web) {
            if (!filter_var($web, FILTER_VALIDATE_URL)) { // 合法URL
                return errorJsonReturn('Parameter validation failed');
            }
            $is_web = 1;
        } else {
            $is_web = 0;
        }

        switch ($is_top) { //判断是否置顶
            case 'true':
                $is_top = 1;
                break;
            case 'false':
                $is_top = 0;
                break;
            default:
                return errorJsonReturn('Parameter validation failed');
                break;
        }
        switch ($is_enable) { //判断是否启用
            case 'true':
                $is_enable = 1;
                break;
            case 'false':
                $is_enable = 0;
                break;
            default:
                return errorJsonReturn('Parameter validation failed');
                break;
        }
        $state = json_decode(authcode($establish, 'DECODE', config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode")), true);
        // 判断有没有超时30分钟
        if ($state['time'] + 1800 < time()) {
            return json_decode(errorJsonReturn("Other-10000")->getContent(), true);
        }
        foreach ($coverList as $key => $value) {
            unset($coverList);
            $coverList = $value;
        }
        if (!$state['establish']) { //修改/保存漫画
            try {
                $RawData = Db::table('classified_catalogue')
                    ->where([
                        "_id" => $class_id,
                    ])
                    ->find();


                Db::table('classified_catalogue')
                    ->where([
                        "_id" => $class_id,
                    ])
                    ->update([
                        "title" => $title, #分类标题
                        "original_name" => "cover.png", #分类标题图片名
                        "path" => $coverList['imagesId'], #分类标题图片名路径
                        "file_server" => $coverList['fileServer'], #分类标题图片名路径
                        "is_web" => $is_web, #是不是网页
                        "active" => $is_top, #是不是 置顶
                        "link" => $web, #要是网页的话网页的链接
                        "description" => $description, #描述
                        "enable" => $is_enable, #是否启用
                    ]);

                Db::table('log_classified_catalogue')
                    ->insert([
                        "original_title" => $RawData['title'], //'分类标题'
                        "original_original_name" => $RawData['original_name'], //'分类标题图片名'
                        "original_path" => $RawData['path'], //'分类标题图片名'
                        "original_file_server" => $RawData['file_server'], //'分类标题图片名路径'
                        "original_is_web" => $RawData['is_web'], //'是不是网页'
                        "original_active" => $RawData['active'], //'是不是置顶'
                        "original_link" => $RawData['link'], //'要是网页的话网页的链接'
                        "original_description" => $RawData['description'], //'描述'
                        "enable" => $RawData['enable'], //'是否启用'
                        "new_title" => $title, //'新分类标题'
                        "new_original_name" => "cover.png", //'新分类标题图片名'
                        "new_path" => $coverList['imagesId'], //'新分类标题图片名'
                        "new_file_server" => $coverList['fileServer'], //'新分类标题图片名路径'
                        "new_is_web" => $is_web, //'新是不是网页'
                        "new_active" => $is_top, #是 , //'新是不是置顶'
                        "new_link" => $web, //'新要是网页的话网页的链接'
                        "new_description" => $description, //'新描述'
                        "new_enable" => $is_enable, //'新是否启用'
                        "insert_user_id" => $user_info["_id"], //'修改人id'
                        "_id" => randIdStructure(6), //'id'
                    ]);
                return successJsonReturn(["state" => 1]);
            } catch (\Throwable $th) {
                var_dump($th);
            }
        } else { //创建漫画


            $CreateID = randIdStructure(123456789);
            $class_info = Db::table('classified_catalogue')
                ->where([
                    "title" => $title,
                ])
                ->find();
            if ($class_info) { //判断我要插入的数据有没有存在数据表
                return errorJsonReturn("undefined error", '插入的表已存在');
            }
            $sql =
                "CREATE TABLE `book_info_categories_info_$CreateID` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '本条数id',
                `book_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '书籍id',
                `state` int(1) DEFAULT NULL COMMENT '是否允许显示本列表1 显示 0隐藏',
                `add_user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '添加用户id',
                `add_time` datetime DEFAULT NULL COMMENT '添加时间',
                PRIMARY KEY (`id`)
                ) ENGINE=InnoDB AUTO_INCREMENT=366 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='分类详细信息 分类名字 $title';
                ";
            try {

                Db::query($sql);
                $class_info = Db::table('classified_catalogue')
                    ->insert([
                        "title" => $title, #分类标题
                        "original_name" => "cover.png", #分类标题图片名
                        "path" => $coverList['imagesId'], #分类标题图片名路径
                        "file_server" => $coverList['fileServer'], #分类标题图片名路径
                        "is_web" => $is_web, #是不是网页
                        "active" => $is_top, #是不是 置顶
                        "link" => $web, #要是网页的话网页的链接
                        "description" => $description, #描述
                        "enable" => $is_enable, #是否启用
                        "_id" => $CreateID,
                        "user_id" => $user_info['_id'],
                        "state" => 1,
                    ]);
                return successJsonReturn(["state" => 2]);
            } catch (\Throwable $th) {
                var_dump($th);
                return errorJsonReturn('创建数据表失败', "创建数据表失败请重新填写或刷新");
            }

            /*  $conn = mysqli_connect(config("database.hostname"), config("database.username"), config("database.password"), config("database.database"), config("database.hostport"));
            if (mysqli_query($conn, $sql)) {
                echo "数据表 MyGuests 创建成功";
            } else {
                echo "创建数据表错误: " . mysqli_error($conn);
            }

            mysqli_close($conn); */
        }
    }
    public function updateState()
    {
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        # 更新分类状态
        $class_id =  input("get.class_id");
        $title =  input("post.title");
        $id =  input("post.id");

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";
        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        $ParseUserToken = VerificationToken(input("post.token"), $encodeData, $key1, $key2);
        if ($ParseUserToken['code'] != 200) {
            return json($ParseUserToken);
        }

        $userJurisdiction = selectSuperUserJurisdiction($user_info['_id'], ['edit_class_info']);
        if ($userJurisdiction['code'] != 200) {
            return json($userJurisdiction);
        }
        if ($userJurisdiction['data']['state'] != 1) { //判断用户状态 必须是正常
            return json_decode(errorJsonReturn("User-10003")->getContent(), true);
        }
        if ($userJurisdiction['data']['edit_class_info'] != 1) { //判断用户权限 1代表有权限操作
            return json_decode(errorJsonReturn("User-10004")->getContent(), true);
        }

        $classInfo = Db::table('classified_catalogue')
            ->where([
                "_id" => $class_id,
                "title" => $title,
                "id" => $id,
            ])
            ->field(["enable"])
            ->find();
        if (!$classInfo) {
            return errorJsonReturn('Parameter validation failed');
        }
        if ($classInfo['enable'] == 1) {
            $update = [
                "enable" => 0,
            ];
        } else {
            $update = [
                "enable" => 1,
            ];
        }
        try {
            Db::table('classified_catalogue')
                ->where([
                    "_id" => $class_id,
                    "title" => $title,
                    "id" => $id,
                ])
                ->update($update);
            return successJsonReturn(["enable" => $update['enable']]);
        } catch (\Throwable $th) {
            return errorJsonReturn('发生意外错误', "发生意外错误");
        }
    }
    public function deleteAndRecoveryClass()
    {



        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        # 更新分类状态
        $class_id =  input("get.class_id");
        $title =  input("post.title");
        $id =  input("post.id");

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";
        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        $ParseUserToken = VerificationToken(input("post.token"), $encodeData, $key1, $key2);
        if ($ParseUserToken['code'] != 200) {
            return json($ParseUserToken);
        }

        $userJurisdiction = selectSuperUserJurisdiction($user_info['_id'], ['edit_class_info']);
        if ($userJurisdiction['code'] != 200) {
            return json($userJurisdiction);
        }
        if ($userJurisdiction['data']['state'] != 1) { //判断用户状态 必须是正常
            return json_decode(errorJsonReturn("User-10003")->getContent(), true);
        }
        if ($userJurisdiction['data']['edit_class_info'] != 1) { //判断用户权限 1代表有权限操作
            return json_decode(errorJsonReturn("User-10004")->getContent(), true);
        }


        $classInfo = Db::table('classified_catalogue')
            ->where([
                "_id" => $class_id,
                "title" => $title,
                "id" => $id,
            ])
            ->field(["state",])
            ->find();
        if (!$classInfo) {
            return errorJsonReturn('Parameter validation failed');
        }
        if ($classInfo['state'] == 1) {
            $update = [
                "state" => 0,
            ];
        } else {
            $update = [
                "state" => 1,
            ];
        }
        try {
            Db::table('classified_catalogue')
                ->where([
                    "_id" => $class_id,
                    "title" => $title,
                    "id" => $id,
                ])
                ->update($update);
            return successJsonReturn(["state" => $update['state']]);
        } catch (\Throwable $th) {
            return errorJsonReturn('发生意外错误', "发生意外错误");
        }
    }
    public function enterDeleteClass()
    {
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        # 更新分类状态
        $class_id =  input("get.class_id");
        $title =  input("post.title");
        $id =  input("post.id");

        $encodeData  = $user_info['_id'] . $token . "ClassifiedCatalogue";
        $key1 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionBase256");
        $key2 = config("useradminConfig.useradmin_ClassifiedAndTagsEncryptionAuthcode");
        $ParseUserToken = VerificationToken(input("post.token"), $encodeData, $key1, $key2);
        if ($ParseUserToken['code'] != 200) {
            return json($ParseUserToken);
        }
        $userJurisdiction = selectSuperUserJurisdiction($user_info['_id'], ['edit_class_info']);
        if ($userJurisdiction['code'] != 200) {
            return json($userJurisdiction);
        }
        if ($userJurisdiction['data']['state'] != 1) { //判断用户状态 必须是正常
            return json_decode(errorJsonReturn("User-10003")->getContent(), true);
        }
        if ($userJurisdiction['data']['edit_class_info'] != 1) { //判断用户权限 1代表有权限操作
            return json_decode(errorJsonReturn("User-10004")->getContent(), true);
        }


        $classInfo = Db::table('classified_catalogue')
            ->where([
                "_id" => $class_id,
                "title" => $title,
                "id" => $id,
                "state" => 0,
            ])
            ->find();
        if ($classInfo) {
            // try {

            //删除当前分类的封面图片
            try {
                $class_count = Db::table("book_info_categories_info_$classInfo[_id]")
                    ->count();
            } catch (\Throwable $th) { //被删除的分类 不存在 直接删除这条分类
                Db::table('classified_catalogue')
                    ->where($classInfo)
                    ->delete();
                return successJsonReturn(["deleteClassName" => $title]);
            }
            if ($class_count) {
                return json_decode(errorJsonReturn("ClassifiedAndTags-EnterDeleteClass-10001")->getContent(), true);
            }

            $info = explode("/", $classInfo["path"]);
            $tableName = $info[0];
            $deleteID = $info[1];
            $deleteInfo = Db::table($tableName)
                ->where([
                    "frame_id" => $deleteID,
                ])
                ->find();
            try {
                Filesystem::disk("ClassImages")->delete("$deleteInfo[path]");
            } catch (\Throwable $th) {
                //删除失败有可能文件不存在
            }
            //删除封面所在表的记录
            Db::table($tableName)
                ->where([
                    "frame_id" => $deleteID,
                ])
                ->delete();
            //删除表
            $sql = "DROP TABLE book_info_categories_info_$classInfo[_id]";
            Db::query($sql);
            Db::table('classified_catalogue')
                ->where($classInfo)
                ->delete();
            return successJsonReturn(["deleteClassName" => $title]);
            // } catch (\Throwable $th) {
            // return errorJsonReturn('发生意外错误', "发生意外错误");
            // }
        }
    }
}
